package network.socket.tcp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpEchoServer {
    private ServerSocket serverSocket = null;

    public TcpEchoServer(int port) throws IOException {
        this.serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("tcp服务器启动");
        while (true) {
            //和客户端建立交流 使用创建的clientSocket 和具体地客户端进行交流
            Socket clientSocket = serverSocket.accept();
            System.out.printf("客户端IP：%s%n", clientSocket.getInetAddress().getHostAddress());
            System.out.printf("客户端端口号：%s%n", clientSocket.getPort());
            // 5.接收客户端的数据，需要从客户端Socket中的输入流获取
            System.out.println("接收到客户端请求：");
            InputStream is = clientSocket.getInputStream();
            // 为了方便获取字符串内容，可以将以上字节流包装为字符流
            BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String line;
            // 一直读取到流结束：TCP是基于流的数据传输，一定要客户端关闭Socket输出流才表示服务端接收IO输入流结束
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
            // 6.双方关闭连接：服务端是关闭客户端socket连接
            clientSocket.close();
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer tcpEchoServer = new TcpEchoServer(8888);
        tcpEchoServer.start();
    }
}
